import { requestApi } from '../../../api';
import { formatImage } from '../../../utils/formatImage';
import { formatPrice } from '../../../utils/util';
const app = getApp();

Page({
    data: {
        startX: 0,
        startY: 0,
        lists: [],
        lastIndex: [],
        channel: 'wx_xcx',
    },
    onLoad(options) {
        if (!app.toLogin()) {
            return false
        }

        let channel = options.channel || 'wx_xcx';

        this.setData({
            channel
        })
    },
    onShow() {
        this.getList();
    },
    getList() {
        const { channel } = this.data;

        // wx.showLoading({
        //   title: '加载中...',
        // });

        app.request({
            url: requestApi.footprint,
            data: {
                channel,
                is_new_ver: true
            }
        }, (d) => {
            if (d.original.ret_code == 200) {
                const item_list = [];
                d.original.data.item_list.forEach((item, index) => {
                    if (item.type == 273) {
                        item.data.product_cover_image.full_path = formatImage.cdnImage(item.data.product_cover_image.path, formatImage.THUMBNAIL_M);
                        item.data.tax_price_txt = item.data.tax_price ? formatPrice(item.data.tax_price / 100) : '';
                        item.data.goods_price_txt = item.data.goods_price ? formatPrice(item.data.goods_price / 100) : '';
                        item.data.original_price_txt = item.data.original_price ? formatPrice(item.data.original_price / 100) : '';
                        item.data.item_type = 3;
                        item.data.isTouchMove = false;
                    }

                    if (item.type == 443) {
                        item.data.cover_image.full_path = formatImage.cdnImage(item.data.cover_image.path, formatImage.THUMBNAIL_M);
                        item.data.item_type = item.data.type * 1 + 1;
                        item.data.isTouchMove = false;
                    }

                    item.data.item_code = item.type;
                    item.data.key = '' + item.data.item_type + index + (item.data.gid ? item.data.gid : item.data.tid);
                    
                    if (item.type == 442) {
                        item_list.push({
                            time: item.data.time,
                            child: []
                        });
                    } else {
                        item_list[item_list.length - 1]['child'].push(item.data)
                    }
                });

                this.setData({
                    lists: item_list
                });
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
            // wx.hideLoading();
        })
    },
    jumpGoods(e) {
        const { channel } = this.data;
        const gid = e.currentTarget.dataset.gid;

        wx.navigateTo({
            url: '../../goods/goodsDetail/goodsDetail?gid=' + gid + '&channel=' + channel
        })
    },
    jumpTopic(e) {
        const { channel } = this.data;
        const { info } = e.currentTarget.dataset;

        if (info.type == 0) {
            wx.navigateTo({
                url: '/pages/topic/topicDetail/topicDetail?tid=' + info.tid + '&channel=' + channel
            })
        } else if (info.type == 1) {
            const isFlasSale = info.protocol.indexOf('flashSale') >= 0;

            if (isFlasSale) {
                const params = 'channel=' + channel;
                wx.navigateTo({
                    url: `/pages/webView/webView?urlParams=${encodeURIComponent(params)}&type=flashsale&tid=${info.tid}`,
                })
            } else {
                wx.navigateTo({
                    url: '/pages/activity/activityDetail/activityDetail?tId=' + info.tid + '&channel=' + channel
                })
            }
        }
    },
    findSame(e) {
        const { channel } = this.data;
        const { product_brandname_e, final_level_type_id } = e.currentTarget.dataset.info;

        wx.navigateTo({
            url: '/pages/categoryHall/categoryHall?keywords=' + product_brandname_e + '&goods_type_id=' + final_level_type_id + '&channel=' + channel
        })
    },
    // 手指触摸开始事件，记录开始的(X,Y)位置
    touchStart: function (e) {
        const { lists, lastIndex } = this.data;
        const currentIndex = e.currentTarget.dataset.index //当前索引
        const last = lastIndex.join(',');

        // 将上一次触摸的item
        if (last && last != currentIndex) {
            lists[lastIndex[0]].child[lastIndex[1]].isTouchMove = false;
        }

        // 更新数据，记录开始的位置
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            lastIndex: currentIndex.split(','),
            lists
        })
    },
    // 手指滑动事件
    touchMove: function (e) {
        // 定义变量进行数据存储
        const { lists, lastIndex, startX, startY } = this.data;
        let currentIndex = e.currentTarget.dataset.index //当前索引
        let touchMoveX = e.changedTouches[0].clientX // 滑动变化X坐标
        let touchMoveY = e.changedTouches[0].clientY//滑动变化坐标
        const last = lastIndex.join(',');

        //获取滑动角度
        let angle = this.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
        //滑动超过30度角 return
        if (Math.abs(angle) > 30) return;

        if (last == currentIndex) {
            if (touchMoveX > startX) {
                // 滑动位置大于开始位置 => 右滑
                lists[lastIndex[0]].child[lastIndex[1]].isTouchMove = false;
            } else {
                // => 左滑
                lists[lastIndex[0]].child[lastIndex[1]].isTouchMove = true;
            }
        }

        //更新数据
        this.setData({
            lists
        })
    },
        /**
     * 计算滑动角度
     * @param {Object} start 起点坐标
     * @param {Object} end 终点坐标
     */
    angle (start, end) {
        var _X = end.X - start.X,
            _Y = end.Y - start.Y;
        //返回角度 /Math.atan()返回数字的反正切值
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    handleDeleteProduct (e) {
        const { info, idx, index } = e.currentTarget.dataset;
        let type = info.item_type, id = info.gid || info.tid;
        let userinfo = wx.getStorageSync('userinfo') || {};
        let { lists } = this.data;

        if (index >= 0) {
            wx.showLoading({
                title: '删除中...',
            });  

            app.request({
                url: requestApi.delUserBrowsing,
                method: "POST",
                data: {
                    id,
                    login_uid: userinfo.uid,
                    type,
                    is_new_ver: true
                }
            }, (d) => {
                if (d.original.ret_code == 200) {
                    lists[idx].child.splice(index, 1);
            
                    if (lists[idx].child.length < 1) {
                        lists.splice(idx, 1);
                    }
        
                    this.setData({
                        lists
                    });
                }
            }, (error) => {
                wx.showModal({
                    title: '提示',
                    showCancel: false,
                    content: error,
                })
            }, () => {
                wx.hideLoading();
            })
        }
    },
    goHome() {
        wx.switchTab({
          url: '/pages/index/index',
        })
    }
})